package com.aaa.sso.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;

import java.util.Date;
import java.util.Map;

/**
 * @ fileName:JwtUtils
 * @ description: JWT工具类
 * @ author:zhz
 * @ createTime:2023/6/16 16:30
 * @ version:1.0.0
 */
public class JwtUtils {
    //密钥，只在服务端声明  不能暴露给客户端
    private static final String SECRET = "bsnzgyztmngd";
    /**
     * 生成token
     * @param payload 载荷,需要在token中存放的数据
     * @return
     */
    public static String generateToken(Map<String, String> payload) {
        //实例化日历类
       // Calendar instance = Calendar.getInstance();
      //  instance.add(Calendar.DATE, 1);
        JWTCreator.Builder builder = JWT.create();
        //载荷,生成token中保存的信息    :: 方法引用
        payload.forEach(builder::withClaim);
       /*for (Map.Entry<String, String> stringStringEntry : payload.entrySet()) {
            builder.withClaim(stringStringEntry.getKey(), stringStringEntry.getValue());
        }*/
        //流式编程
        return builder.withAudience("admin") //签发对象
                .withIssuedAt(new Date()) //发行时间
                //.withExpiresAt(instance.getTime()) //过期时间
                .sign(Algorithm.HMAC256(SECRET)); //加密算法+盐
    }
    /**
     * 校验token,有异常,即为校验失败
     *
     * @param token token数据
     * @return
     */
    public static boolean verify(String token) {
        try {
            JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
    /**
     * 根据token获取载荷信息
     *
     * @param token token数据
     * @return
     */
    public static Map<String, Claim> getPayloadByToken(String token) {
        try {
            return JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token).getClaims();
        }  catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
       /* Map<String, String> payload = new HashMap<>();
        payload.put("userId", "1001");
        payload.put("userName", "zhangsan");
        payload.put("email", "zhangsan@163.com");
        //...按照自己的需求，可以随便放值 但是不能放敏感信息
        String token = generateToken(payload);
        System.out.println("生成的token-------------"+token);*/

        //验证token
        boolean verify = verify("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiJhZG1pbiIsInVzZXJOYW1lIjoiYWRtaW4iLCJ1c2VySWQiOiIxIiwiaWF0IjoxNjg2OTY0NTQ2fQ.bLZNHF2OJxZTJJk-11MQnGkYnydjgWbg9z-Cn26NEfQ");
        System.out.println(verify);

        //根据token可以获取载荷
        /*Map<String, Claim> payloadByToken = getPayloadByToken("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiJhZG1pbiIsInVzZXJOYW1lIjoiemhhbmdzYW4iLCJ1c2VySWQiOiIxMDAxIiwiaWF0IjoxNjg2OTA1MjIwLCJlbWFpbCI6InpoYW5nc2FuQDE2My5jb20ifQ.bdaNIkJIXxhtlFPCt1rzilWyKd5xGZI30XZUHXCwpBk");
        //payloadByToken.forEach((t,u)->{ System.out.println(t+"--------"+u); });
        System.out.println("-------------------------------------------------------------");
        for (Map.Entry<String, Claim> stringClaimEntry : payloadByToken.entrySet()) {
            System.out.println(stringClaimEntry.getKey()+"========="+stringClaimEntry.getValue().toString()
                    .replace("\"", ""));
        }*/
        String token = "admin-eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiJhZG1pbiIsInVzZXJOYW1lIjoiYWRtaW4iLCJ1c2VySWQiOiIxIiwiaWF0IjoxNjg2OTcyMDQwfQ.n4OlOhlzFLran3hHg_1XlvEYBeJk3SaazfuDUi3is0Q";
        String tokenSub = token.substring(token.indexOf("-") + 1);
        //String[] tokenArray = token.split("-");
        //System.out.println(tokenArray[1]);
        System.out.println(tokenSub);
        System.out.println(verify(tokenSub));

    }

}
